<?php

namespace app\admin\model\facrm\qywx;


use EasyWeChat\Factory;
use fast\Random;
use think\Db;
use think\Exception;
use think\Model;

class Contacts extends Model
{


    // 表名
    protected $name = 'facrm_qywx_contacts';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    public $error = "";

    /**
     * 获取本地微信客户
     * @param $row $external_userid or external
     * @param $config
     * @param array $extend
     * @return Contacts|array|bool|false|\PDOStatement|string|Model
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getContacts($row, $config, $extend = array())
    {
        if (is_string($row)){
            //不存在就去同步企业微信
            $appc = Factory::work([
                'corp_id' => $config['corp_id'],
                'secret' => $config['customer_secret'], // 客户的 secret
            ]);
            $external_c = $appc->external_contact->get($row);
            if (!$external_c || $external_c['errcode'] != '0' || !$external_c['external_contact']) {
                $this->error = (__("获取信息失败"));
            }
            $external_contact = $external_c['external_contact'];
            $follow_user = $external_c['follow_user'];
        }else{
            $external_contact = $row['external_contact'];
            $follow_user = $row['follow_info'];
        }

        $external_userid=$external_contact['external_userid'];
        $qywxContacts = $this->where('external_userid', $external_userid)->find();
        if (!$qywxContacts) {
            //插入本地数据
            $external_contact['corp_id'] = $config['corp_id'];
            $qywxContacts = $this->allowField(true)->create(array_merge($external_contact, ['follow_user' => json_encode($follow_user)]), true);
            Db::startTrans();
            try {

                $customer_id = 0;
                $customer_name = isset($external_contact['corp_full_name']) ? $external_contact['corp_full_name'] :
                    $external_contact['name'] . "@" . $this->buildShort($external_contact['external_userid']);//如果不是企业用户
                $remark_mobiles = isset($follow_user[0]['remark_mobiles'][0]) ? $follow_user[0]['remark_mobiles'][0] : '';

                //获取crm配置
                $addon_config = get_addon_config('facrm');
                $customerModel = new \app\admin\model\facrm\Customer();
                switch ($addon_config['unique']) {
                    case 'name':
                        $customer_id = $customerModel->where('name', $customer_name)->value('id');
                        break;
                    case 'mobile':
                        if ($remark_mobiles) {
                            $customer_id = $customerModel->where('mobile', $remark_mobiles)->value('id');
                        }
                        break;
                }
                //如果本地数据库不存在客户 就添加
                if (!$customer_id) {
                    //customer表插入和判断规格
                    //如果有corp_full_name把该信息以公司名称存储，如果没有就以备注手机为条件存储
                    $tags = "";
                    $tags_arr = array(__($external_contact['type'] == 1 ? "微信用户" : "企业微信"));
                    if (isset($follow_user[0]['tags']) && $follow_user[0]['tags']) {
                        foreach ($follow_user[0]['tags'] as $tag) {
                            if ($tags_arr && in_array($tag['tag_name'], $tags_arr)) continue;
                            $tags_arr[] = $tag['tag_name'];
                        }
                        $tags = implode(",", $tags_arr);
                    }
                    //添加未本地客户 默认为第一个跟进人
                    $add_customer =
                        [
                            'name' => $customer_name,
                            'mobile' => $remark_mobiles,
                            'telephone' => isset($follow_user[0]['remark_mobiles'][1]) ? $follow_user[0]['remark_mobiles'][1] : '',//用电话记录第二个联系方式
                            'source' => $config['source'],
                            'tags' => $tags,
                            'create_user_id' => $extend['admin_id'],
                            'owner_user_id' => $extend['admin_id'],
                            'next_time' => time(),//提醒跟进
                            'follow_time' => time(),
                            'collect_time' => time(),
                            'remark' => (isset($follow_user[0]['remark']) ? $follow_user[0]['remark'] : '') . "@" . __($external_contact['type'] == 1 ? "微信用户" : "企业微信"),
                        ];
                    $customer_id = $customerModel->add($add_customer, 0, 0,false);
                }

                $qywxContacts->customer_id = $customer_id;
                $qywxContacts->save();
                Db::commit();

            } catch (\Exception $e) {
                Db::rollback();
            }

        } else {
            //更新
            $qywxContacts->isUpdate(true)->allowField(true)
                ->update(array_merge($external_contact, ['follow_user' => json_encode($follow_user)]),
                    ['external_userid' => $external_userid], true);

        }
        return $qywxContacts;
    }


    /**
     * 客户对象
     * @return \think\model\relation\BelongsTo
     */
    public function customer()
    {
        return $this->belongsTo('\app\admin\model\facrm\Customer', 'customer_id', 'id');
    }

    /**
     * 转化成短字符
     * @param $str
     * @return string
     */
    protected function buildShort($str)
    {

        $result = sprintf("%u", crc32($str));
        $show = '';
        while ($result > 0) {
            $s = $result % 62;
            if ($s > 35) {
                $s = chr($s + 61);
            } elseif ($s > 9 && $s <= 35) {
                $s = chr($s + 55);
            }
            $show .= $s;
            $result = floor($result / 62);
        }

        return $show;

    }

}